
package com.platform.modules.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.sys.entity.SysSmsLogEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.form.SysLoginForm;
import com.platform.modules.sys.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author
 */
@RestController
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @Autowired
    private SysSmsLogService sysSmsLogService;
    @Autowired
    private JedisUtil jedisUtil;

    @Autowired
    private SysConfigService sysConfigService;
    /**
     * 验证码
     *
     * @param response response
     * @param uuid     uuid
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }


    public static void main(String[] args) {
//        System.out.println(new Sha256Hash("dyjr@!2203", "olzpgKZA4BKU8KMMz7Uw").toHex());
        System.out.println(new Sha256Hash("888888", "H4OANaXydyvjgIZRghd7").toHex());
    }
    @PostMapping("/sys/getSmsCode")
    public RestResponse getSmsCode(@RequestBody SysLoginForm form){
        SysUserEntity user = sysUserService.queryByUserName(form.getUserName());
        String password;
        try {
            // AESUtil.desEncrypt解密后 password 为char[16], trim转为char[6]
            password = AESUtil.desEncrypt(form.getPassword()).trim();
        } catch (Exception e) {
            return RestResponse.error("解密失败！");
        }

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return RestResponse.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return RestResponse.error("账号已被锁定,请联系管理员");
        }

        if(StringUtils.isBlank(user.getMobile())){
            return RestResponse.error("该用户没有绑定手机号码,请联系管理员");
        }

        String mobile = user.getMobile();
        String code = jedisUtil.get(Constant.SYS_SMS + user.getMobile());
        // 一分钟之内不能重复发送短信
        String stint = jedisUtil.get(Constant.SYS_SMS + user.getMobile());
        String smsCode;
        if (StringUtils.isNotBlank(stint)) {
            return RestResponse.success("短信已发送");
        } else {
            if (StringUtils.isNotBlank(code)) {
                smsCode = code;
            } else {
                //生成验证码
                smsCode = CharUtil.getRandomNum(6);
            }
        }
        SysSmsLogEntity smsLog = new SysSmsLogEntity();
        JSONObject js = new JSONObject();
        js.put("code", smsCode);
        smsLog.setContent(js.toJSONString());
        smsLog.setCode(smsCode);
        smsLog.setMobile(mobile);
//        sysSmsLogService.sendSms(userEntity.getId(), smsLog, templateId);
        sysSmsLogService.sendSms(user.getUserId(), smsLog);
        //发送成功之后将验证码存入redis，有效期为5分钟
        jedisUtil.set(Constant.SYS_SMS + mobile, smsCode, 300);
        jedisUtil.set(Constant.SYS_VERIFICATIONSNUMBER + 1, smsCode, 300);
        return RestResponse.success("短信已发送");
    }

    /**
     * 登录
     *
     * @param form 登录表单
     * @return RestResponse
     */
    @SysLog("登录")
    @PostMapping("/sys/login")
    public RestResponse login(@RequestBody SysLoginForm form) {
        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
        if (!captcha) {
            return RestResponse.error("图片验证码不正确");
        }
        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUserName());
        String password;
        try {
            // AESUtil.desEncrypt解密后 password 为char[16], trim转为char[6]
            password = AESUtil.desEncrypt(form.getPassword()).trim();
        } catch (Exception e) {
            return RestResponse.error("解密失败！");
        }

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return RestResponse.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 0) {
            return RestResponse.error("账号已被锁定,请联系管理员");
        }

//        checkSmsCode( form.getSmsCode() , user.getMobile());

        //生成token，并保存到数据库
        String token = sysUserTokenService.createToken(user.getUserId());

        return RestResponse.success().put("token", token).put("expire", Constant.EXPIRE);
    }


    /**
     * 退出系统
     *
     * @return RestResponse
     */
    @PostMapping("/sys/logout")
    public RestResponse logout() {
        sysUserTokenService.logout(getUserId());
        return RestResponse.success();
    }


    public void checkSmsCode(String code ,String mobile) {
        String smsCode = jedisUtil.get(Constant.SYS_SMS + mobile);
        if (org.apache.commons.lang3.StringUtils.isBlank(smsCode)) {
                throw new BusinessException("短信验证码错误");
        } else {
            if (StringUtils.isNullOrEmpty(smsCode)) {
                throw new BusinessException("短信验证码已失效，请重新获取");
            }
            if (!code.equals(smsCode)) {
                Integer vNumber;
                if(StringUtils.isBlank(jedisUtil.get(Constant.SYS_VERIFICATIONSNUMBER + mobile))){
                    vNumber = 0;
                } else {
                    vNumber = Integer.valueOf(jedisUtil.get(Constant.SYS_VERIFICATIONSNUMBER + mobile));
                }
                if (vNumber > 5) {
                    jedisUtil.del(Constant.SYS_SMS + mobile);
                    jedisUtil.del(Constant.SYS_VERIFICATIONSNUMBER + mobile);
                } else {
                    vNumber++;
                    jedisUtil.set(Constant.SYS_VERIFICATIONSNUMBER + mobile, String.valueOf(vNumber), 300);
                }
                throw new BusinessException("短信验证码错误");
            }

        }
    }

}
